//
//  WBMainViewController.swift
//  MyWeiBo
//
//  Created by 俞存旭 on 16/9/23.
//  Copyright © 2016年 俞存旭. All rights reserved.
//

import UIKit

class WBMainViewController: UITabBarController {

    
    //MARK: 私有控件
    lazy var composeBUtton: UIButton = UIButton(type: .custom)
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildControllers()
        setupComposeButton()
    }
    /*
     portrait  : 竖屏
     landscape : 横屏
     
     - 使用代码控制设备的方向，好处，可以在需要横屏的时候，单独处理
     - 设置支持的方向之后，当前的控制器及子控制器都会尊守这个方向
     - 如果播放视频，通常是通过modal展现的
     */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        
        return .portrait
        
    }
    
    //MARK: 撰写按钮监听方法
    func composeStatue()
    {
        print("撰写微博")
        
        //测试方向旋转
        let vc = UIViewController()
        vc.view.backgroundColor = setColor2()
        
        let nav = UINavigationController(rootViewController: vc)
        
        present(nav, animated: true, completion: nil)
    }
    
    func setColor2() -> UIColor {
        let red = CGFloat(arc4random_uniform(255))/CGFloat(255.0)
        let green = CGFloat( arc4random_uniform(255))/CGFloat(255.0)
        let blue = CGFloat(arc4random_uniform(255))/CGFloat(255.0)
        return UIColor.init(red:red, green:green, blue:blue , alpha: 1)
        
    }

}


/*
 1.extension 类似于OC中的分类。在Swift中还可以用来切分代码块，可以把相近功能的函数，放在一个extension中，便于维护代码
 2.注意：和OC分类一样，extension中不能定义属性
 */
//MARK: - 设置界面
extension WBMainViewController {

    //设置撰写按钮
    func setupComposeButton()
    {
        tabBar.addSubview(composeBUtton)
        composeBUtton.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        composeBUtton.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: .highlighted)
        composeBUtton.setImage(UIImage(named: "tabbar_compose_icon_add") , for: .normal)

        let count = CGFloat(childViewControllers.count)
        let w = (tabBar.bounds.width / count)-1

        composeBUtton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        composeBUtton.addTarget(self, action: #selector(composeStatue), for: .touchUpInside)
    }
    //设置所以子控制器
    func setupChildControllers() {
        
        //0.获取沙盒json路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        //加载data
        var data = NSData(contentsOfFile: jsonPath);
        //判断data是否有内容，如果没有，说明本地沙盒没有文件
        if data == nil {
            let path = Bundle.main.path(forResource: "main.json", ofType: nil);
            data = NSData(contentsOfFile: path!);
            
        }
        //data一定有一个内容，反序列化
        
        
        //从bundle加载配置的json
        //1.路径 2.加载NSData 3.f反序列化转换为数组
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: Any]]

            else {
            
            return
        }
        
        /*
        let array: [[String: Any]] = [
            ["clsName" : "WBHomeViewController","title" : "首页","imageName" : "home","visitorInfo" : ["imageName":"","message":"关注一些人，回这里看看有什么惊喜"]],
            
            ["clsName" : "WBMessageViewController","title" : "消息","imageName" : "message_center","visitorInfo" : ["imageName":"visitordiscover_image_discover","message":"登录后，别人评论你的微博，发给你的消息，都会在这里收到通知"]],
            
            ["clsName" : "UIViewController"],
            
            ["clsName" : "WBDiscoverViewController","title" : "发现","imageName" : "discover","visitorInfo" : ["imageName":"visitordiscover_image_discover","message":"登录后，最新、最热微博尽在掌握，不在与事实潮流擦肩而过"]],
            
            ["clsName" : "WBProfileViewController","title" : "我","imageName" : "profile","visitorInfo" : ["imageName":"visitordiscover_image_profile","message":"登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]]
        ]
        //测试数据格式是否正确- 转换为plist数据更加直观
        //(array as NSArray).write(toFile: "Users/yucunxu/Desktop/demo.plist", atomically: true)
        //数组 ->json序列化
        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        let fileURL = NSURL.fileURL(withPath: "")
        (data as NSData).write(toFile: "Users/yucunxu/Desktop/demo.json", atomically: true)
        */
        
        
        //遍历数组，循环创建控制器数组
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        //设置tabbar子控制器
        viewControllers = arrayM
    }
    //使用字典创建一个子控制器
    private func controller(dict:[String: Any]) -> UIViewController {
        
        //1.获取字典内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
            let visitorDict = dict["visitorInfo"] as? [String : String]
            else {
                
                return UIViewController()
        }
        let vc = cls.init()
        vc.title = title
        
        
        //设置控制器访客信息字典
        vc.viditorInfoDictionary = visitorDict
        
        //设置tabbar图片
        vc.tabBarItem.image = UIImage(named: "tabbar_"+imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_"+imageName+"_selected")?.withRenderingMode(.alwaysOriginal)//图片渲染
        //设置tabbar标题颜色
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.init(red: 255/255.0, green: 130/255.0, blue: 0/255.0, alpha: 1.0)], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12)], for: .normal)
        // 实例化导航控制器的时候，会调用push方法将rootVC压栈
        let nav = WBNavigationController(rootViewController: vc)
        return nav
        
    }
}



























